<template>
  <div>
<!--待解决问题  为什么await对antv的图生成无效，在await处拿到数据，接下来的画图里的数据却为空？-->
<!-- 汇总信息 总的容器 总的占用率-->
  <h3 class="title">云手机容器测试数据</h3>
    <el-select v-model="value4" clearable placeholder="请选择云手机容器" multiple style="width: 200px">
      <el-option
          v-for="item in containerOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
      </el-option>
    </el-select>
    <el-select v-model="value6" clearable placeholder="请选择云手机容器启动方式" style="margin-left: 10px">
      <el-option
          v-for="item in startMethodsOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
      </el-option>
    </el-select>
<!--    <el-button type="primary" style="margin-left: 10px" class="el-icon-search" size="small">查询</el-button>-->
    <el-date-picker
        v-model="value3"
        type="datetimerange"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        align="right"
        style="margin-left: 10px"
    >
    </el-date-picker>
    <el-input v-model="value5" placeholder="输入1-60的间隔分钟整数" style="width: 180px;margin-left: 10px"></el-input>

    <!--    <el-input v-model="value" placeholder="请输入云手机容器名称" clearable style="width: 200px"></el-input>-->

    <el-button type="primary" style="margin-left: 10px" class="el-icon-search" size="small" @click="generateGraph">图表生成</el-button>
    <el-button type="primary" style="margin-left: 10px;float:right;" class="el-icon-download" size="small" @click="serverInfoExport">导出</el-button>
<!--    汇总信息-->
    <div style="font-size: 15px"><span style="color: red">数据总览：</span><span>CPU平均使用率{{containerPerfTotalData.cpu_total_used.toFixed(2)}}% </span><span class="spanStyle">GPU平均使用率{{containerPerfTotalData.gpu_total_used.toFixed(2)}}% </span> <span class="spanStyle">内存平均使用率{{containerPerfTotalData.ram_total_used.toFixed(2)}}%</span>   </div>
    <div style="display: flex;justify-content: space-between">
      <div style="width: 49%">
        <title-componet name="云手机容器测试信息列表" v-if="this.$store.state.titleState"></title-componet>
        <el-table
          class="InfoData"
          :data="this.$dataPage(this.testTableData,this.testCurrentPage,this.testPageSize).pageData"
          :header-cell-style="this.$handleheader"
          :row-style="this.$rowstyle"
          :cell-style="this.$cellstyle"
          border
          ref="multipleTable"
      >
        <!--    <el-table-column-->
        <!--        type="selection"-->
        <!--        width="55">-->
        <!--    </el-table-column>-->
        <el-table-column
            prop="id"
            label="编号"
            width="60"
            header-align="center"
            align="center"
        >
        </el-table-column>
        <!--    <el-table-column-->
        <!--        prop="container_id"-->
        <!--        label="云手机容器编号"-->
        <!--        header-align="center"-->
        <!--    >-->
        <!--    </el-table-column>-->
        <el-table-column
            prop="container_name"
            label="云手机容器名称"
            header-align="center"
        >
        </el-table-column>
        <el-table-column
            prop="container_cpu_used"
            label="云手机容器CPU占用率(%)"
            :formatter="this.$fixTwo"
            header-align="center"
        >
        </el-table-column>
        <el-table-column
            prop="container_gpu_used"
            label="云手机容器GPU占用率(%)"
            :formatter="this.$fixTwo"
            header-align="center"
        >
        </el-table-column>
        <el-table-column
            prop="container_ram_used"
            label="云手机容器内存占用率(%)"
            :formatter="this.$fixTwo"
            header-align="center"
        >
        </el-table-column>
        <!--    <el-table-column-->
        <!--        prop="time"-->
        <!--        label="测评时间"-->
        <!--        width="200"-->
        <!--        sortable-->
        <!--        header-align="center"-->
        <!--    >-->
        <!--    </el-table-column>-->
<!--        <el-table-column-->
<!--            label="操作"-->
<!--            header-align="center"-->
<!--            align='center'-->
<!--            width="100"-->
<!--        >-->
<!--          <template slot-scope="scope">-->
<!--            <el-button type="text" style="margin-left: 10px">删除</el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
        <page :current-page="testCurrentPage" :page-size="testPageSize" :total="testTotal" @handleChange="handleCurrentChange"></page>
        <div class="explain">注：选择云手机容器及其启动方式即可生成实时图表；历史数据需要选择容器并填入时间段与间隔数</div>
      </div>
      <div style="width: 49%">
        <title-componet name="云手机容器测试信息可视化" v-if="this.$store.state.titleState"></title-componet>
        <el-tabs v-model="testDataActiveName" style="margin-top: 10px;" v-show="this.realCpuData.length!==0 || this.cpuData.length!==0">
          <el-tab-pane label="实时" name="first"></el-tab-pane>
          <!--      <el-tab-pane label="硬盘" name="second"></el-tab-pane>-->
          <el-tab-pane label="历史" name="second"></el-tab-pane>
<!--          <el-tab-pane label="GPU1" name="third"></el-tab-pane>-->
          <!--      <el-tab-pane label="GPU2数据" name="seventh"></el-tab-pane>-->
          <!--      <el-tab-pane label="GPU3数据" name="eighth"></el-tab-pane>-->
          <!--      <el-tab-pane label="GPU4数据" name="ninth"></el-tab-pane>-->
<!--          <el-tab-pane label="CPU" name="fourth"></el-tab-pane>-->
          <!--      <el-tab-pane label="CPU多核心数据" name="sixth"></el-tab-pane>-->

        </el-tabs>

        <div v-if="isStart">正在运行，请稍后</div>
        <div v-loading="loading"></div>
        <div class="outer" v-show="testDataActiveName==='first'">
<!--          <p style="text-align: center" v-show="realArea3">无实时数据</p>-->
          <p style="text-align: center" v-show="realArea1">内存占用率(%)</p>
          <div id="real1" style="height: 150px;width: 100%;margin-top: 10px" >
          </div>
          <p style="text-align: center" v-show="realArea2">CPU占用率(%)</p>
<!--          <p style="text-align: center" v-show="realArea2"></p>-->
          <div id="real2" style="height: 150px;width: 100%" ></div>
          <p style="text-align: center" v-show="realArea3">GPU1占用率(%)</p>
          <div id="real3" style="height: 150px;width: 100%"></div>

        </div>
        <div class="outer" v-show="testDataActiveName==='second'">
          <!--          <p style="text-align: center" v-show="realArea3">无实时数据</p>-->
          <p style="text-align: center" v-show="ramArea">内存占用率(%)</p>
          <div id="ram" style="height: 150px;width: 100%;margin-top: 10px" >
          </div>
          <p style="text-align: center" v-show="cpuArea">CPU占用率(%)</p>
          <!--          <p style="text-align: center" v-show="realArea2"></p>-->
          <div id="cpu" style="height: 150px;width: 100%;margin-top: 10px" ></div>
          <p style="text-align: center" v-show="gpuArea">GPU1占用率(%)</p>
          <div id="gpu" style="height: 150px;width: 100%;margin-top: 10px"></div>

        </div>
<!--        <div class="outer" v-show="testDataActiveName==='second'">-->
<!--          <h3 class="title2">内存占用率(%)</h3>-->
<!--&lt;!&ndash;          <p style="text-align: center" v-show="!ramArea">无内存数据</p>&ndash;&gt;-->
<!--          <div id="ram" style="height: 150px;width: 100%;">-->

<!--          </div>-->
<!--          <h3 class="title2">CPU占用率(%)</h3>-->
<!--&lt;!&ndash;          <p style="text-align: center" v-show="!cpuArea">无CPU数据</p>&ndash;&gt;-->
<!--          <div id="cpu" style="height: 150px;width: 100%"></div>-->
<!--&lt;!&ndash;          <p style="text-align: center" v-show="!gpuArea">无GPU数据</p>&ndash;&gt;-->
<!--          <div id="gpu" style="height: 150px;width: 100%"></div>-->
<!--        </div>-->
<!--        <div class="outer" v-show="testDataActiveName==='fourth'">-->
<!--          <h3 class="title2">CPU占用率(%)</h3>-->
<!--          <p style="text-align: center" v-show="!cpuArea">无CPU数据</p>-->
<!--&lt;!&ndash;          <div id="cpu" style="height: 350px;width: 100%"></div>&ndash;&gt;-->
<!--        </div>-->
<!--        <div class="outer" v-show="testDataActiveName==='third'">-->
<!--          <h3 class="title2">GPU占用率(%)</h3>-->
<!--          <p style="text-align: center" v-show="!gpuArea">无GPU数据</p>-->
<!--&lt;!&ndash;          <div id="gpu" style="height: 350px;width: 100%"></div>&ndash;&gt;-->
<!--        </div>-->

      </div>
    </div>
    <el-dialog
        title="导出信息填写"
        :visible.sync="exportVisible"
        width="30%"
        :show-close="false"
        :close-on-click-modal="false">

      <el-form ref="form" :model="exportForm" label-width="80px" inline :rules="exportRules">
        <el-form-item label="文件名" prop="name">
          <el-input v-model="exportForm.name"></el-input>
        </el-form-item>
        <el-form-item label="高度" prop="height">
          <el-input v-model="exportForm.height"></el-input>
        </el-form-item>
        <el-form-item label="宽度" prop="width">
          <el-input v-model="exportForm.width"></el-input>
        </el-form-item>
      </el-form>
<!--      <span style="color: red">*高度建议不超过500，宽度不超过1000</span>-->
      <span style="color: red">{{wh}}</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="exportVisible = false">取 消</el-button>
        <el-button type="primary" @click="exportWord(exportForm.height,exportForm.width,'testData3',exportForm.name),exportVisible=false" v-if="ramData.length">确 定</el-button>
        <el-button type="primary" @click="exportWord(exportForm.height,exportForm.width,'testData2',exportForm.name),exportVisible=false" v-else-if="realRamData.length">确 定</el-button>
        <el-button type="primary" @click="startExport('testData1',testTableData,'testTableData'),exportVisible=false" v-else>确 定</el-button>
        </span>
    </el-dialog>

  </div>

</template>

<script>
import {Line} from "@antv/g2plot";
import moment from "moment";
import Page from "@/components/page";
import TitleComponet from "@/components/titleComponet";
import {toDataURL} from "@/components/exportFunction";
import JSZipUtils from "jszip-utils";
import PizZip from "pizzip";
import docxtemplater from "docxtemplater";
import {exportMixin} from "@/components/mixin";
import {
  containerAllList,
  containerPerfTotal,
  oneContainerCpuHistoryPerf,
  oneContainerGpuHistoryPerf,
  oneContainerRamHistoryPerf, oneContainerRealPerf, runningContainerList,
  startMultiContainer, startSingleContainer
} from "@/api/perf";

const {getWH} = require("../components/getWH");
export default {
  name: "cloudPhoneManager",
  components: {TitleComponet, Page},
  mixins : [exportMixin],
  data() {
    return{
      wh:'',
      testDataActiveName:'first',
      value5:'',
      value3:'',
      loading:false,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近1小时',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近3小时',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 3);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近12小时',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 12);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近1天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近7天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近30天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, ]
      },
      testTableData:null,
      testCurrentPage:1,
      testPageSize:10,
      testTotal:'',
     options: [{
     value: '选项1',
     label: '视频流'
   }, {
     value: '选项2',
     label: '指令流'
   }],
      value: '',
      value2:[],
      line:null,
      inter:null,
      tableInterval:null,
      graphInterval1:null,
      graphInterval2:null,
      graphData:[],
      chartInstance:null,
      containerOptions:[],
      startMethodsOptions:[{
        value : 'keep',
        label : '保留其他容器'
      },{
        value : 'del',
        label : '删除其他容器'
      }],
      value4:'',
      value6 : '',
      cpuData:[],
      gpuData:[],
      ramData:[],
      realCpuData:[],
      realGpuData:[],
      realRamData:[],
      realArea1:null,
      realArea2:null,
      realArea3:null,
      cpuArea:null,
      gpuArea:null,
      ramArea:null,
      Area: {
        realArea1:null,
        realArea2:null,
        realArea3:null,
        cpuArea:null,
        gpuArea:null,
        ramArea:null,
      },
      multiSelection:[],
      isStart :false,
      containerPerfTotalData:null
    }
  },
  beforeDestroy() {
    clearInterval(this.tableInterval)
    this.tableInterval =null
    clearInterval(this.graphInterval1)
    this.graphInterval1 =null
    clearInterval(this.graphInterval2)
    this.graphInterval2 =null
  },
  created() {

    this.initContainerData()
    // this.initData()
    this.initTestTableData()
    this.getAllInfo()
    // this.tableInterval=setInterval(() =>{
    //   this.initTestTableData()
    //   this.getAllInfo()
    // },3000)

  },
  methods:{
    async ramDataGet() {
      for (let g=0;g<this.value4.length;g++){
        await oneContainerRamHistoryPerf(this.value4[g],moment(this.value3[0]).format('YYYY-MM-DD HH:mm:ss'),moment(this.value3[1]).format('YYYY-MM-DD HH:mm:ss'),this.value5).then(res1=>{
          console.log('ramGet',res1)
          // axios.get(this.$ip2 + '/container/perf/ramtime?container_id=' + this.value4[g] + '&&start_time=' + moment(this.value3[0]).format('YYYY-MM-DD HH:mm:ss') + '&end_time=' + moment(this.value3[1]).format('YYYY-MM-DD HH:mm:ss') + '&period=' + this.value5).then(res1 => {
          for (let i = 0; i < res1.data.ram_used.length; i++) {
            this.ramData.push({
              timePeriod: moment(res1.data.ram_used[i][0]).format('YYYY-MM-DD HH:mm'),
              value: +res1.data.ram_used[i][1],
              // category必须是字符串
              category:'容器名称:'+res1.data.container_name
            })
          }
        })
      }
      console.log('怎么说',this.ramData);
    },
    async cpuDataGet() {
      for (let g=0;g<this.value4.length;g++){
        await oneContainerCpuHistoryPerf(this.value4[g],moment(this.value3[0]).format('YYYY-MM-DD HH:mm:ss'),moment(this.value3[1]).format('YYYY-MM-DD HH:mm:ss'),this.value5).then(res1=>{
          console.log('cpuGet',res1);

          // axios.get(this.$ip2 + '/container/perf/cputime?container_id=' + this.value4[g] + '&&start_time=' + moment(this.value3[0]).format('YYYY-MM-DD HH:mm:ss') + '&end_time=' + moment(this.value3[1]).format('YYYY-MM-DD HH:mm:ss') + '&period=' + this.value5).then(res1 => {
          for (let i = 0; i < res1.data.cpu_used.length; i++) {
            this.cpuData.push({
              timePeriod: moment(res1.data.cpu_used[i][0]).format('YYYY-MM-DD HH:mm'),
              value: +res1.data.cpu_used[i][1],
              // category必须是字符串
              category: '容器名称:'+res1.data.container_name
            })
          }
        })
      }
      console.log("cpuData",this.cpuData)
    },
    async gpuDataGet() {
      for (let g=0;g<this.value4.length;g++){
        await oneContainerGpuHistoryPerf(this.value4[g],moment(this.value3[0]).format('YYYY-MM-DD HH:mm:ss'),moment(this.value3[1]).format('YYYY-MM-DD HH:mm:ss'),this.value5).then(res1=>{
          console.log('gpuGet',res1);
          // axios.get(this.$ip2 + '/container/perf/gputime?container_id=' + this.value4[g] + '&&start_time=' + moment(this.value3[0]).format('YYYY-MM-DD HH:mm:ss') + '&end_time=' + moment(this.value3[1]).format('YYYY-MM-DD HH:mm:ss') + '&period=' + this.value5).then(res1 => {
          for (let i = 0; i < res1.data.gpu_used.length; i++) {
            this.gpuData.push({
              timePeriod: moment(res1.data.gpu_used[i][0]).format('YYYY-MM-DD HH:mm'),
              value: +res1.data.gpu_used[i][1],
              // category必须是字符串
              category: '容器名称:'+res1.data.container_name
            })
          }
        })
      }
    },
    async testFn() {
      await this.ramDataGet();
      await this.cpuDataGet();
      await this.gpuDataGet();
      console.log('ramData看看',this.gpuData);
      console.log('cpuData看看',this.gpuData);
      await console.log('gpuData看看',this.gpuData);
      this.ramArea = new Line('ram', {
        data: this.ramData,
        xField: 'timePeriod',
        yField: 'value',
        seriesField: 'category',
        xAxis: {
          range: [0, 1],
        },
      });
      this.cpuArea = new Line('cpu', {
        data: this.cpuData,
        xField: 'timePeriod',
        yField: 'value',
        seriesField: 'category',
        xAxis: {
          range: [0, 1],
        },
      });
      this.gpuArea = new Line('gpu', {
        data: this.gpuData,
        xField: 'timePeriod',
        yField: 'value',
        seriesField: 'category',
        xAxis: {
          range: [0, 1],
        },
      });
      this.ramArea.render()
      this.gpuArea.render()
      this.cpuArea.render()
      console.log('cpu',this.cpuArea);
      this.isStart = false
      this.loading = false
    },
    //一起生成算了
    generateGraph() {
      console.log('5',this.value5);
      console.log('3',this.value3);
      console.log('4',this.value4);
      console.log('6',this.value6);
      let twoV
      let oneV
      this.graphInterval1 =null
      clearInterval(this.graphInterval1)
      this.graphInterval2 =null
      clearInterval(this.graphInterval2)
      if ((this.value5<1||this.value5>60) && this.value5!=='') {
        this.$message({
          message: '输出超出范围，请重新输入',
          type: 'warning'
        });
        this.value5 =''
      }
      // 没有填入时间或间隔 生成实时
      else if (this.value5 ==='' && (this.value3 === null || this.value3 === '') && this.value4.length !==0 && this.value6 !== ''){
        this.isStart = true
        this.loading = true
        if (this.cpuArea || this.realArea1){
          this.graphDestory()
        }
        if (this.value4.length >=2 && this.value6 !== '') {

          // twoV = this.value4[0] + ',' + this.value4[1]
          let twoV = ''
          for (let i = 0; i < this.value4.length; i ++) {
            twoV +=this.value4[i]
            if (i !== this.value4.length - 1) {
              twoV +=','
            }

          }
          this.$message('容器正在启动');
          if (this.value6 === 'del') {
            startMultiContainer(twoV).then(res=>{
            // axios.get(this.$ip2 +'/container/starts/?container_list=' + twoV).then(res=>{
              console.log(res.data);
              this.isStart = false
              this.loading = false
              let value4 = this.value4
              let len = value4.length
              this.graphInterval1 = setInterval(()=>{
                for (let i =0;i<len;i++) {
                  oneContainerRealPerf(value4[i]).then(res=>{
                    console.log('oneContainerRealPerf',res)
                  // axios.get(this.$ip2+'/container/perf/get?container_id=' + this.value4[i]).then(res=>{
                    // console.log(res);
                    this.realCpuData.push({
                      timePeriod:moment(res.data.time).format('YYYY-MM-DD HH:mm:ss'),
                      value:+res.data.container_cpu_used,
                      category: '容器:'+res.data.container_name
                    })
                    this.realGpuData.push({
                      timePeriod:moment(res.data.time).format('YYYY-MM-DD HH:mm:ss'),
                      value:+res.data.container_gpu_used,
                      category: '容器:'+res.data.container_name
                    })
                    this.realRamData.push({
                      timePeriod:moment(res.data.time).format('YYYY-MM-DD HH:mm:ss'),
                      value:+res.data.container_ram_used,
                      category: '容器:'+res.data.container_name
                    })

                  })
                }
              },6000)
              this.generateRealDataGraph()
            })
          }
          else if (this.value6 === 'keep') {
            startSingleContainer(twoV).then(res=>{

              // axios.get(this.$ip2 +'/container/start/?container_list=' + twoV).then(res=>{
              console.log('huangwei',res.data);
              this.isStart = false
              this.loading = false
              let value4 = this.value4
              let len = value4.length
              this.graphInterval1 = setInterval(()=>{
                for (let i =0;i<len;i++) {
                  console.log("one")
                  oneContainerRealPerf(value4[i]).then(res=>{
                    console.log('oneContainerRealPerf',res)
                  // axios.get(this.$ip2+'/container/perf/get?container_id=' + this.value4[i]).then(res=>{
                    // console.log(res);
                    this.realCpuData.push({
                      timePeriod:moment(res.data.time).format('YYYY-MM-DD HH:mm:ss'),
                      value:+res.data.container_cpu_used,
                      category: '容器:'+res.data.container_name
                    })
                    this.realGpuData.push({
                      timePeriod:moment(res.data.time).format('YYYY-MM-DD HH:mm:ss'),
                      value:+res.data.container_gpu_used,
                      category: '容器:'+res.data.container_name
                    })
                    this.realRamData.push({
                      timePeriod:moment(res.data.time).format('YYYY-MM-DD HH:mm:ss'),
                      value:+res.data.container_ram_used,
                      category: '容器:'+res.data.container_name
                    })

                  })
                }
              },6000)
              this.generateRealDataGraph()
            })
          }

        }
        else if (this.value4.length === 1 && this.value6 !== ''){
          this.$message('容器正在启动');
          oneV = this.value4[0]
          if (this.value6 === 'del') {
            startMultiContainer(oneV).then(async res=>{
            // axios.get(this.$ip2 +'/container/starts/?container_list=' + oneV).then(async res=>{
              console.log(res.data);
              this.isStart = false
              this.loading = false
              let value4 = this.value4
              let len = value4.length
              this.graphInterval1 = setInterval(()=>{
                for (let i =0;i<len;i++) {
                  oneContainerRealPerf(value4[i]).then(res=>{
                  // axios.get(this.$ip2+'/container/perf/get?container_id=' + this.value4[i]).then(res=>{
                    // console.log(res);
                    this.realCpuData.push({
                      timePeriod:moment(res.data.time).format('YYYY-MM-DD HH:mm:ss'),
                      value:+res.data.container_cpu_used,
                      category: '容器:'+res.data.container_name
                    })
                    this.realGpuData.push({
                      timePeriod:moment(res.data.time).format('YYYY-MM-DD HH:mm:ss'),
                      value:+res.data.container_gpu_used,
                      category: '容器:'+res.data.container_name
                    })
                    this.realRamData.push({
                      timePeriod:moment(res.data.time).format('YYYY-MM-DD HH:mm:ss'),
                      value:+res.data.container_ram_used,
                      category: '容器:'+res.data.container_name
                    })

                  })
                }
              },6000)
              this.generateRealDataGraph()
            })
          }
          else if (this.value6 === 'keep') {
            console.log('ali')
            startSingleContainer(oneV).then(res=>{
            // axios.get(this.$ip2 +'/container/start/?container_list=' + oneV).then(async res=>{
              console.log(res.data);
              this.isStart = false
              this.loading = false
              let value4 = this.value4
              let len = value4.length
              this.graphInterval1 = setInterval(()=>{
                for (let i =0;i<len;i++) {
                  oneContainerRealPerf(value4[i]).then(res=>{
                    console.log('oneContainerRealPerf',res)
                  // axios.get(this.$ip2+'/container/perf/get?container_id=' + this.value4[i]).then(res=>{
                    // console.log(res);
                    this.realCpuData.push({
                      timePeriod:moment(res.data.time).format('YYYY-MM-DD HH:mm:ss'),
                      value:+res.data.container_cpu_used,
                      category: '容器:'+res.data.container_name
                    })
                    this.realGpuData.push({
                      timePeriod:moment(res.data.time).format('YYYY-MM-DD HH:mm:ss'),
                      value:+res.data.container_gpu_used,
                      category: '容器:'+res.data.container_name
                    })
                    this.realRamData.push({
                      timePeriod:moment(res.data.time).format('YYYY-MM-DD HH:mm:ss'),
                      value:+res.data.container_ram_used,
                      category: '容器:'+res.data.container_name
                    })

                  })
                }
              },6000)
              this.generateRealDataGraph()
            })
          }
        }
        else {
          this.$message('请阅读下方的注,选择和输入正确的选项');
        }

        // this.graphInterval1 = setInterval(()=>{
        //   for (let i =0;i<this.value4.length;i++) {
        //       axios.get(this.$ip2+'/container/perf/get?container_id=' + this.value4[i]).then(res=>{
        //         // console.log(res);
        //         this.realCpuData.push({
        //           timePeriod:res.data.time,
        //           value:res.data.container_cpu_used,
        //           category: '容器:'+this.value4[i]
        //         })
        //         this.realGpuData.push({
        //           timePeriod:res.data.time,
        //           value:res.data.container_gpu_used,
        //           category: '容器:'+this.value4[i]
        //         })
        //         this.realRamData.push({
        //           timePeriod:res.data.time,
        //           value:res.data.container_ram_used,
        //           category: '容器:'+this.value4[i]
        //         })
        //
        //       })
        //   }
        // },6000)
        // this.generateRealDataGraph()

        // this.testFn()
      }
      // 三个均填入 只查看历史
      else if (this.value4.length!==0 &&this.value3 !==null && this.value5 !== ''){
        // console.log('来咯',this.cpuArea.type)
        console.log('来咯',typeof this.cpuArea)
        if (this.cpuArea || this.realArea1){
          console.log("??")
          this.graphDestory()
          console.log('qinghlema',this.cpuArea);
        }
        this.isStart = true
        this.loading = true
        this.testFn()
      }
      else {
        this.$message({
          message: '输入不合规:只选择容器及其启动方式，则会显示实时折线图；选择容器、填入时间与间隔，则会显示历史折线图',
          type: 'warning'
        });
      }


    },
    //初始化表格
    initTestTableData() {
      // this.tableInterval=setInterval(() =>{
      runningContainerList(this.$store.state.server.serverId).then(res=>{
        // axios.get(this.$ip2 +'/container/perf/all?server_id=' + this.$store.state.server.serverId).then(res=>{
            this.testTableData = res.data
            this.testTotal=res.data.length
            for (let i =0;i<res.data.length;i++){
              this.testTableData[i].id =  i + 1
              // this.containerOptions.push({
              //   value:res.data[i].container_id,
              //   label:res.data[i].container_id
              // })
            }
        })
      // },3000)
    },
    //获取总览信息
    getAllInfo() {
      containerPerfTotal(this.$store.state.server.serverId).then(res=>{
      // axios.get(this.$ip2 + '/container/perf/total?server_id=' + this.$store.state.server.serverId).then(res=>{
        this.containerPerfTotalData = res.data
      })
      // containerPerfTotal(this.$store.state.server.serverId).then(res=>{
      //
      // })
    },
    handleCurrentChange(val) {
      this.testCurrentPage =val
    },
    initContainerData() {
      containerAllList().then(res=>{
      // axios.get(this.$ip2 +'/container/all').then(res=>{
        for (let i =0;i<res.data.length;i++){
          this.containerOptions.push({
            value:res.data[i].container_id,
            label:res.data[i].container_name
          })
        }
      })
    },
    generateRealDataGraph() {
      this.realArea1 = new Line('real1', {
        data: this.realRamData,
        xField: 'timePeriod',
        yField: 'value',
        seriesField:'category',
        // point: {
        //   size: 2,
        //   shape: 'custom-point',
        //   style: {
        //     fill: 'white',
        //     stroke: '#5B8FF9',
        //     lineWidth: 2,
        //   },
        // },
        // label:{
        //   visible:true,
        //   offsetX: 6,
        //   offsetY: 6,
        // },
        // yAxis:{
        //   //这是实现y轴固定的关键
        //   type:'linear',
        //   max: 100,
        //   min:0,
        //   // tickCount:40,
        //
        // },
        xAxis: {
          range: [0, 1],
          // tickCount: 32,
          // label:{
          //   autoRotate:false,
          //   //这里是弧度而不是角度
          //   rotate:30.4,
          //   offsetX:-75
          // }
        },
        // slider: {
        //   start: 0,
        //   end: 1,
        // },

      });
      this.realArea2 = new Line('real2', {
        data: this.realCpuData,
        xField: 'timePeriod',
        yField: 'value',
        seriesField:'category',
        // point: {
        //   size: 2,
        //   shape: 'custom-point',
        //   style: {
        //     fill: 'white',
        //     stroke: '#5B8FF9',
        //     lineWidth: 2,
        //   },
        // },
        // label:{
        //   visible:true,
        //   offsetX: 6,
        //   offsetY: 6,
        // },
        // yAxis:{
        //   //这是实现y轴固定的关键
        //   type:'linear',
        //   max: 100,
        //   min:0,
        //   // tickCount:40,
        //
        // },
        xAxis: {
          range: [0, 1],
          // tickCount: 32,
          // label:{
          //   autoRotate:false,
          //   //这里是弧度而不是角度
          //   rotate:30.4,
          //   offsetX:-75
          // }
        },
        // slider: {
        //   start: 0,
        //   end: 1,
        // },

      });
      this.realArea3 = new Line('real3', {
        data: this.realGpuData,
        xField: 'timePeriod',
        yField: 'value',
        seriesField:'category',
        // point: {
        //   size: 2,
        //   shape: 'custom-point',
        //   style: {
        //     fill: 'white',
        //     stroke: '#5B8FF9',
        //     lineWidth: 2,
        //   },
        // },
        // label:{
        //   visible:true,
        //   offsetX: 6,
        //   offsetY: 6,
        // },
        // yAxis:{
        //   //这是实现y轴固定的关键
        //   type:'linear',
        //   max: 100,
        //   min:0,
        //   // tickCount:40,
        //
        // },
        xAxis: {
          range: [0, 1],
          // tickCount: 32,
          // label:{
          //   autoRotate:false,
          //   //这里是弧度而不是角度
          //   rotate:30.4,
          //   offsetX:-75
          // }
        },
        // slider: {
        //   start: 0,
        //   end: 1,
        // },

      });
      this.realArea1.render()
      this.realArea2.render()
      this.realArea3.render()
      this.graphInterval2 = setInterval(()=>{
        this.realArea2.changeData(this.realCpuData)
        this.realArea1.changeData(this.realRamData)
        this.realArea3.changeData(this.realGpuData)
        // console.log(this.realRamData);
      },500)
    },
    generateHistoryDataGraph(){
      this.ramArea = new Line('ram', {
        data: this.ramData,
        xField: 'timePeriod',
        yField: 'value',
        seriesField:'category',
        // point: {
        //   size: 2,
        //   shape: 'custom-point',
        //   style: {
        //     fill: 'white',
        //     stroke: '#5B8FF9',
        //     lineWidth: 2,
        //   },
        // },
        // label:{
        //   visible:true,
        //   offsetX: 6,
        //   offsetY: 6,
        // },
        // yAxis:{
        //   //这是实现y轴固定的关键
        //   type:'linear',
        //   max: 100,
        //   min:0,
        //   // tickCount:40,
        // },
        xAxis: {
          // type:'time',
          range: [0, 1],
          tickCount: 32,
          label:{
            autoRotate:false,
            //这里是弧度而不是角度
            rotate:30.4,
            offsetX:-75
          }
        },
        slider: {
          start: 0,
          end: 1,
        },

      });
      this.gpuArea = new Line('gpu', {
        data: this.gpuData,
        xField: 'timePeriod',
        yField: 'value',
        seriesField:'category',
        // point: {
        //   size: 2,
        //   shape: 'custom-point',
        //   style: {
        //     fill: 'white',
        //     stroke: '#5B8FF9',
        //     lineWidth: 2,
        //   },
        // },
        // label:{
        //   visible:true,
        //   offsetX: 6,
        //   offsetY: 6,
        // },
        // yAxis:{
        //   //这是实现y轴固定的关键
        //   type:'linear',
        //   max: 100,
        //   min:0,
        //   // tickCount:40,
        //
        // },
        xAxis: {
          range: [0, 1],
          tickCount: 32,
          label:{
            autoRotate:false,
            //这里是弧度而不是角度
            rotate:30.4,
            offsetX:-75
          }
        },
        slider: {
          start: 0,
          end: 1,
        },

      });
      this.cpuArea = new Line('cpu', {
        data: this.cpuData,
        xField: 'timePeriod',
        yField: 'value',
        seriesField:'category',
        // point: {
        //   size: 2,
        //   shape: 'custom-point',
        //   style: {
        //     fill: 'white',
        //     stroke: '#5B8FF9',
        //     lineWidth: 2,
        //   },
        // },
        // label:{
        //   visible:true,
        //   offsetX: 6,
        //   offsetY: 6,
        // },
        // yAxis:{
        //   //这是实现y轴固定的关键
        //   type:'linear',
        //   max: 100,
        //   min:0,
        //   // tickCount:40,
        //
        // },
        xAxis: {
          range: [0, 1],
          tickCount: 32,
          label:{
            autoRotate:false,
            //这里是弧度而不是角度
            rotate:30.4,
            offsetX:-75
          }
        },
        slider: {
          start: 0,
          end: 1,
        },

      });
      this.cpuArea.render()
      this.gpuArea.render()
      this.ramArea.render()
      console.log(this.ramArea);
      // setInterval(()=>{
      //   this.ramArea.changeData(this.ramData)
      //   this.cpuArea.changeData(this.cpuData)
      //   this.gpuArea.changeData(this.gpuData)
      // },500)
    },

    graphDestory() {
      if (this.realArea1) {
        this.realArea1.destroy()
        this.realArea2.destroy()
        this.realArea3.destroy()
        this.realArea1 = null
        this.realArea2 = null
        this.realArea3 = null
      }

      if (this.cpuArea){
        this.cpuArea.destroy()
        this.gpuArea.destroy()
        this.ramArea.destroy()
        this.cpuArea = null
        this.gpuArea = null
        this.ramArea = null
      }

      this.ramData=[]
      this.cpuData=[]
      this.gpuData=[]
      this.realCpuData=[]
      this.realGpuData=[]
      this.realRamData=[]
    },
    serverInfoExport() {
      if (this.ramArea) {
        this.wh = getWH('ram')
        console.log(this.gpuArea,this.cpuArea,this.ramArea)
      }
      else if (this.realArea1) {
        this.wh = getWH('real1')
      }
      else {
        this.wh = '当前没有图表,高宽任意输入'
      }
      this.exportVisible = true
    },
    getImg() {
      // var img = new Image();
      // img.src = this.chartInstance.getDataURL({
      //   pixelRatio: 2,
      //   backgroundColor: '#fff',
      //   type: 'png'
      // })
      if (this.realArea1) {
        this.Area.realArea1 = toDataURL(this.realArea1.chart)
      }
      if (this.realArea2) {
        this.Area.realArea2 = toDataURL(this.realArea2.chart)
      }
      if (this.realArea3) {
        this.Area.realArea3 = toDataURL(this.realArea3.chart)
      }
      if (this.cpuArea && this.testDataActiveName === 'second') {
        this.Area.cpuArea = toDataURL(this.cpuArea.chart)
      }
      if (this.gpuArea && this.testDataActiveName === 'second') {
        this.Area.gpuArea = toDataURL(this.gpuArea.chart)
      }
      if (this.ramArea && this.testDataActiveName === 'second') {
        this.Area.ramArea = toDataURL(this.ramArea.chart)
      }

      // this.tableData.imgUrl = img.src
      // console.log('src', toDataURL(this.line.chart))
    },
    // Echarts图片处理
    base64DataURLToArrayBuffer(dataURL) {
      const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
      if (!base64Regex.test(dataURL)) {
        return false;
      }
      const stringBase64 = dataURL.replace(base64Regex, "");
      let binaryString;
      if (typeof window !== "undefined") {
        binaryString = window.atob(stringBase64);
      } else {
        binaryString = new Buffer(stringBase64, "base64").toString("binary");
      }
      const len = binaryString.length;
      const bytes = new Uint8Array(len);
      for (let i = 0; i < len; i++) {
        const ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
      }
      return bytes.buffer;
    },
    //导出为word
    exportWord(height,width,module,name) {
      this.getImg();
      //这里要引入处理图片的插件，下载docxtemplater后，引入的就在其中了
      const ImageModule = require('docxtemplater-image-module-free');
      const _this = this;
      //Word路径，在public文件下(CLI3)
      JSZipUtils.getBinaryContent(`${module}.docx`, function (error, content) {
        if (error) {
          throw error
        }
        let opts = {}
        opts.centered = true;
        opts.fileType = "docx";
        opts.getImage = (tag) => {
          return _this.base64DataURLToArrayBuffer(tag);
        }
        opts.getSize = () => {
          return [width, height]//这里可更改输出的图片宽和高
        }

        let zip = new PizZip(content);
        let doc = new docxtemplater();
        doc.attachModule(new ImageModule(opts));
        doc.loadZip(zip);
        // 这里是设置导出的数据
        doc.setData({
          testTableData : _this.testTableData,
          Area : _this.Area
          // arr: _this.arr // 评语
        })
        try {
          doc.render()
        } catch (error) {
          var e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties,
          }
          console.log(JSON.stringify({
            error: e
          }));
          throw error;
        }
        const out = doc.getZip().generate({
          type: "blob",
          mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        })
        saveAs(out, `${name}.docx`)
      })
    },
    exportWordWithoutGraph(module,name) {
      // this.getImg();
      // //这里要引入处理图片的插件，下载docxtemplater后，引入的就在其中了
      // const ImageModule = require('docxtemplater-image-module-free');
      const _this = this;
      //Word路径，在public文件下(CLI3)
      JSZipUtils.getBinaryContent(`${module}.docx`, function (error, content) {
        if (error) {
          throw error
        }
        let opts = {}
        opts.centered = true;
        opts.fileType = "docx";
        // opts.getImage = (tag) => {
        //   return _this.base64DataURLToArrayBuffer(tag);
        // }
        // opts.getSize = () => {
        //   return [height, width]//这里可更改输出的图片宽和高
        // }

        let zip = new PizZip(content);
        let doc = new docxtemplater();
        // doc.attachModule(new ImageModule(opts));
        doc.loadZip(zip);
        // 这里是设置导出的数据
        doc.setData({
          fluencyData : _this.fluencyData,
          // exportLine : _this.exportLine
          // arr: _this.arr // 评语
        })
        try {
          doc.render()
        } catch (error) {
          var e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties,
          }
          console.log(JSON.stringify({
            error: e
          }));
          throw error;
        }
        const out = doc.getZip().generate({
          type: "blob",
          mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        })
        saveAs(out, `${name}.docx`)
      })
    },
  },
  mounted() {
    // this.initChart()
    this.tableInterval=setInterval(() =>{
      this.initTestTableData()
      this.getAllInfo()
    },3000)
  }
}
</script>

<style scoped>
.title2 {
  font-size: 20px;
  margin: 5px auto 10px auto;
  text-align: center;
  font-weight: bold;
}
.spanStyle{
  margin-left: 10px;
}
</style>
